<template>
  <div class="page-content">
    <table-bar
      :showTop="false"
      @search="search"
      @reset="resetForm(searchFormRef)"
      @changeColumn="changeColumn"
      :columns="columns"
    >
      <template #top>
        <el-form :model="searchForm" ref="searchFormRef" label-width="82px">
          <el-row :gutter="20">
            <form-input label="账号" prop="name" v-model="searchForm.name" />
            <form-input label="用户名" prop="real_name" v-model="searchForm.real_name" />
            <form-input label="手机号" prop="phone" v-model="searchForm.phone" />
            <form-input label="邮箱" prop="email" v-model="searchForm.email" />
          </el-row>
          <el-row :gutter="20">
            <form-select label="性别" prop="gender" v-model="searchForm.gender" :options="sexOptions" />
            <!-- 这里增加一个空白占位，保持样式美观 -->
            <div style="width: 100%; height: 32px;"></div>
            <div style="width: 100%; height: 32px;"></div>
          </el-row>
        </el-form>
      </template>
      <template #bottom>
        <el-button @click="showDialog('add')" v-ripple>添加用户</el-button>
        <el-button 
          type="danger" 
          @click="batchDelete" 
          v-ripple 
          :disabled="selectedRows.length === 0"
        >批量删除</el-button>
      </template>
    </table-bar>

    <art-table 
      :data="tableData" 
      selection 
      :currentPage="pagination.currentPage" 
      :pageSize="pagination.pageSize" 
      :total="pagination.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @selection-change="handleSelectionChange"
    >
      <template #default>
        <el-table-column
          label="用户名/账号"
          prop="name"
          #default="scope"
          width="300px"
          v-if="columns[0].show"
        >
          <div class="user" style="display: flex; align-items: center">
            <img class="avatar" :src="scope.row.avatar" alt="用户头像" />
            <div>
              <p class="user-name">{{ scope.row.name }}</p>
              <p class="real-name">{{ scope.row.real_name }}</p>
              <p class="email">{{ scope.row.email }}</p>
            </div>
          </div>
        </el-table-column>
        <el-table-column label="手机号" prop="phone" v-if="columns[1].show" />
        <el-table-column label="性别" prop="gender" #default="scope" sortable v-if="columns[2].show">
          {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
        </el-table-column>
        <el-table-column label="部门" prop="dep" #default="scope" v-if="columns[3].show">
          {{ scope.row.group && scope.row.group.length > 0 ? scope.row.group.map(g => g.label).join(', ') : '无' }}
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="created_at"
          sortable
          v-if="columns[5].show"
        />
        <el-table-column fixed="right" label="操作" width="150px">
          <template #default="scope">
            <button-table type="edit" @click="showDialog('edit', scope.row)" />
            <button-table type="delete" @click="deleteUser(scope.row.id)" />
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="30%"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="real_name">
          <el-input v-model="formData.real_name" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="group">
          <el-select v-model="formData.group">
            <el-option 
              v-for="group in groupList" 
              :key="group.id" 
              :label="group.label" 
              :value="group.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="formData.password" type="password" />
        </el-form-item>
        <el-form-item v-if="dialogType === 'add'" label="确认密码" prop="password2">
          <el-input v-model="formData.password2" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { FormInstance } from 'element-plus'
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules } from 'element-plus'
  import { AdminUserService, AdminUserType, UserEditParams } from '@/api/adminUserApi'
  import request from '@/utils/http'
  import { PaginationResult } from '@/types/axios'
  
  // 导入API URL和认证头函数
  const getApiUrl = (endpoint: string): string => {
    const API_PREFIX = import.meta.env.VITE_BASE_URL || '/api';
    return `${API_PREFIX}${endpoint}`;
  }
  
  // 获取认证请求头
  const getAuthHeaders = () => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('accessToken');
    if (!token) return {};
    
    const authToken = token.startsWith('Bearer ') ? token : `Bearer ${token}`;
    return { Authorization: authToken };
  }
  
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const tableData = ref<AdminUserType[]>([])
  const groupList = ref<any[]>([])
  const selectedRows = ref<AdminUserType[]>([])
  
  // 分页
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 表单数据
  const formData = reactive<UserEditParams>({
    name: '',
    real_name: '',
    email: '',
    phone: '',
    gender: 1,
    group: [],
    password: '',
    password2: ''
  })

  const sexOptions = [
    {
      value: 1,
      label: '男'
    },
    {
      value: 2,
      label: '女'
    }
  ]

  const columns = reactive([
    { name: '用户名', show: true },
    { name: '手机号', show: true },
    { name: '性别', show: true },
    { name: '部门', show: true },
    { name: '状态', show: false },
    { name: '创建时间', show: true }
  ])

  const searchFormRef = ref<FormInstance>()
  const searchForm = reactive({
    name: '',         // 账号
    real_name: '',    // 用户名
    phone: '',        // 手机号
    email: '',        // 邮箱
    gender: '',       // 性别
  })

  // 表格行数据处理 - 将后端返回的sex字段处理为前端所需的gender字段
  const processRowData = (row: any) => {
    // 深拷贝防止修改原始数据
    const processedRow = { ...row };
    
    // 处理性别字段
    if (processedRow.sex !== undefined && processedRow.gender === undefined) {
      processedRow.gender = processedRow.sex;
    }
    
    // 确保phone字段存在
    if (processedRow.mobile && !processedRow.phone) {
      processedRow.phone = processedRow.mobile;
    }
    
    return processedRow;
  };

// 获取用户列表数据
const fetchUserList = async () => {
  try {
    const { currentPage, pageSize } = pagination
    
    // 构建查询参数（带where嵌套结构）
    const queryParams: UserQueryParams = {
      page: currentPage,
      pageSize: pageSize,
      where: {  // 所有查询条件移到where对象中
        name: searchForm.name,        // 账号
        real_name: searchForm.real_name, // 真实姓名
        phone: searchForm.phone,      // 手机号
        email: searchForm.email,      // 邮箱
        // 处理性别类型转换（字符串转数字）
        gender: searchForm.gender ? Number(searchForm.gender) : undefined
      }
    }

    // 清理where中的空值（空字符串/undefined）
    if (queryParams.where) {
      // 过滤空值属性
      Object.keys(queryParams.where).forEach(key => {
        const k = key as keyof typeof queryParams.where
        const value = queryParams.where![k]
        
        // 删除空值或空字符串的属性
        if (value === undefined || value === '' || value === null) {
          delete queryParams.where![k]
        }
      })

      // 如果where对象为空则删除该字段
      if (Object.keys(queryParams.where).length === 0) {
        delete queryParams.where
      }
    }

    console.log('[DEBUG] 请求参数:', JSON.stringify(queryParams, null, 2))
    
    const response = await AdminUserService.getUserList(queryParams)
    
    console.log("[DEBUG] 响应数据:", response)

    if (response?.code === 200 && response.data) {
      // 统一处理分页数据结构
      const responseData = response.data

      // 处理两种可能的响应格式：
      // 1. 标准分页结构 { rows: [], total: 0 }
      // 2. 简单数组结构 []
      if (Array.isArray(responseData)) {
        // 无分页的数组响应
        tableData.value = responseData.map(processRowData)
        pagination.total = responseData.length
      } else if (responseData.rows && Array.isArray(responseData.rows)) {
        // 标准分页结构
        tableData.value = responseData.rows.map(processRowData)
        pagination.total = responseData.total || 0
      } else {
        console.error('未知的响应结构:', responseData)
        ElMessage.error('数据格式错误，请联系管理员')
        tableData.value = []
      }
    } else {
      // 处理业务错误
      const errorMsg = response?.message || '获取用户列表失败'
      ElMessage.error(errorMsg)
      tableData.value = []
    }
  } catch (error) {
    // 处理网络错误
    console.error('[ERROR] 获取用户列表出错:', error)
    ElMessage.error({
      message: '请求失败，请检查网络或稍后重试',
      duration: 3000
    })
    tableData.value = []
  } finally {
    // 无论成功失败都关闭loading（如果有）
    loading.value = false
  }
}
  
  // 获取用户组列表
  const fetchUserGroups = async () => {
    try {
      console.log('开始获取用户组列表...');
      const response = await AdminUserService.getUserGroups();
      console.log("获取用户组列表响应:", response);
      
      // 检查响应格式，确保存在data字段
      if (response && response.code === 200 && response.data) {
        // 根据后端返回的数据结构进行适配
        if (Array.isArray(response.data)) {
          // 如果直接返回数组
          groupList.value = response.data;
        } else if (response.data.rows && Array.isArray(response.data.rows)) {
          // 如果返回分页结构
          groupList.value = response.data.rows;
        } else {
          console.warn("用户组列表数据格式不符合预期，使用后备数据");
          // 使用后备数据
          groupList.value = getBackupGroups();
        }
      } else {
        console.warn("获取用户组列表失败，使用后备数据:", response);
        // 设置后备数据
        groupList.value = getBackupGroups();
      }
    } catch (error) {
      console.error('获取用户组列表出错:', error);
      // 设置后备数据
      groupList.value = getBackupGroups();
    }
  }

  // 获取后备用户组数据
  const getBackupGroups = () => {
    return [
      { id: 1, label: '管理组', alias: 'admin', remark: '系统管理员', sort: 1, status: 1 },
      { id: 2, label: '普通用户组', alias: 'user', remark: '普通用户', sort: 2, status: 1 }
    ];
  }

  // 重置表单
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    // 重置后重新查询
    pagination.currentPage = 1
    fetchUserList()
  }

  // 搜索
  const search = () => {
    pagination.currentPage = 1
    fetchUserList()
  }

  // 分页大小变化
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    fetchUserList()
  }

  // 页码变化
  const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    fetchUserList()
  }

  // 打开弹窗
  const showDialog = (type: string, row?: AdminUserType) => {
    dialogVisible.value = true
    dialogType.value = type

    // 重置表单
    Object.keys(formData).forEach(key => {
      formData[key as keyof UserEditParams] = key === 'gender' ? 1 : key === 'group' ? [] : ''
    })

    if (type === 'edit' && row) {
      formData.id = row.id
      formData.name = row.name || ''
      formData.real_name = row.real_name || ''
      formData.email = row.email || ''
      formData.phone = row.mobile || ''
      formData.gender = row.sex !== undefined ? row.sex : 1
      formData.group = row.group && row.group.length > 0 ? row.group.map(g => g.id) : []
      formData.avatar = row.avatar || ''
      
      // 编辑模式下不需要密码字段
      delete formData.password
      delete formData.password2
    }
  }

  // 删除用户
  const deleteUser = (id: number) => {
    ElMessageBox.confirm('确定要删除该用户吗？', '删除用户', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      try {
        // 使用batchDeleteUsers方法，传入ID数组
        const response = await AdminUserService.batchDeleteUsers([id])
        if (response && response.code === 200) {
          ElMessage.success('删除成功')
          fetchUserList() // 重新加载数据
        } else {
          ElMessage.error(response?.message || '删除失败')
        }
      } catch (error) {
        console.error('删除用户出错:', error)
        ElMessage.error('删除用户失败，请稍后再试')
      }
    }).catch(() => {
      // 取消删除，不做处理
    })
  }

  const changeColumn = (list: any) => {
    columns.values = list
  }

  const formRef = ref<FormInstance>()

  // 表单验证规则
  const rules = reactive<FormRules>({
    name: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    email: [
      { required: true, message: '请输入邮箱', trigger: 'blur' },
      { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
    ],
    gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
    group: [{ required: true, message: '请选择部门', trigger: 'change' }],
    password: [
      { required: dialogType.value === 'add', message: '请输入密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
    ],
    password2: [
      { required: dialogType.value === 'add', message: '请确认密码', trigger: 'blur' },
      { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== formData.password) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      }
    ],
    real_name: [
      { required: true, message: '请输入真实姓名', trigger: 'blur' }
    ]
  })

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          let response;

          // 处理提交的数据
          const submitData = { ...formData };
          
          // 确保group是数组
          if (!Array.isArray(submitData.group)) {
            submitData.group = submitData.group ? [Number(submitData.group)] : [];
          }
          
          console.log('提交表单数据:', submitData);
          
          if (dialogType.value === 'add') {
            // 添加用户
            response = await AdminUserService.addUser(submitData);
          } else {
            // 编辑用户 - 使用formData中的id
            if (!submitData.id) {
              const currentRow = tableData.value.find(item => item.name === formData.name);
              if (currentRow) {
                submitData.id = currentRow.id;
              } else {
                ElMessage.error('找不到要编辑的用户信息');
                return;
              }
            }
            
            response = await AdminUserService.updateUser(submitData.id, submitData);
          }
          
          if (response && response.code === 200) {
            ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
            dialogVisible.value = false;
            fetchUserList(); // 重新加载数据
          } else {
            ElMessage.error(response?.message || (dialogType.value === 'add' ? '添加失败' : '更新失败'));
          }
        } catch (error) {
          console.error(dialogType.value === 'add' ? '添加用户出错:' : '更新用户出错:', error);
          ElMessage.error(dialogType.value === 'add' ? '添加失败，请稍后再试' : '更新失败，请稍后再试');
        }
      }
    })
  }
  
  // 页面加载完成后获取数据
  onMounted(() => {
    fetchUserList()
    fetchUserGroups()
  })

  // 处理表格选择变化
  const handleSelectionChange = (selection: AdminUserType[]) => {
    selectedRows.value = selection;
  }
  
  // 批量删除用户
  const batchDelete = () => {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请先选择要删除的用户');
      return;
    }
    
    const userIds = selectedRows.value.map(row => row.id);
    
    ElMessageBox.confirm(
      `确定要删除选中的${selectedRows.value.length}个用户吗？`, 
      '批量删除', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(async () => {
      try {
        const response = await AdminUserService.batchDeleteUsers(userIds);
        if (response && response.code === 200) {
          ElMessage.success('批量删除成功');
          selectedRows.value = []; // 清空选择
          fetchUserList(); // 重新加载数据
        } else {
          ElMessage.error(response?.message || '批量删除失败');
        }
      } catch (error) {
        console.error('批量删除用户出错:', error);
        ElMessage.error('批量删除用户失败，请稍后再试');
      }
    }).catch(() => {
      // 取消删除，不做处理
    });
  }
</script>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    height: 100%;

    .user {
      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 6px;
      }

      > div {
        margin-left: 10px;

        .user-name {
          font-weight: 500;
          color: var(--art-text-gray-800);
        }
        
        .real-name {
          font-size: 13px;
          color: var(--art-text-gray-600);
        }
        
        .email {
          font-size: 12px;
          color: var(--art-text-gray-400);
        }
      }
    }
  }
</style>
